<template>
<div>
  <a-spin :spinning="tableLoad">
  <a-row>
    <a-col :md="18" :xs="24" style="padding-right: 10px;">
      <a-button class="mb10" type="primary" @click="changeData">刷新数据</a-button>
      <div class="card-container">
        <a-tabs type="card" v-model="tabsKey">
          <a-tab-pane v-if="routerShow($route,'data_newData')" tab="实时信息" key="1">
            <a-table :pagination="false" 
              :columns="NewDataFields" 
              :dataSource="NewDataLists"
              :rowKey="record => record.id">
              <div slot="trend" slot-scope="text, record">
                <div :ref="`trend${record.type_id}`" style="width:100%; height:40px;"></div>
              </div>
              <template slot="action" slot-scope="text, record">
                <a-button size="small" class="mr5" type="primary" @click="details(record)">查看</a-button>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane v-if="isAdmin && routerShow($route,'data_sendRegister')" tab="控制信息" key="2">
            <a-table :pagination="false" :columns="SendRegisterFields" :dataSource="SendRegisterLists"
              :rowKey="record => record.id" >
              <template slot="type" slot-scope="text, record">
                <a-input type="number" :placeholder="record.type == 1 ? '整数' : '浮点型'" v-if="record.type == 1 || record.type == 3"  v-model="record.equipment_data"/>
                <a-switch v-else checkedChildren="开" unCheckedChildren="关" v-model="record.isSwitch" />
              </template>
              <template slot="c" slot-scope="text, record">
                <a-button size="small" v-if="routerShow($route,'data_sendOutRegister')" type="primary" @click="controlBtn(record)">下发控制</a-button>
              </template>
              <template slot="action" slot-scope="text, record">
                <a-button size="small" type="primary" @click="controlDetails(record)">查看</a-button>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane tab="统计信息" v-if="routerShow($route,'data_statistics')" key="3">
            <a-table :pagination="false" :columns="StatisticsFields" :dataSource="StatisticsLists"
              :rowKey="record => record.id" >
              <!-- :scroll="{x: 480, y: 700 }" -->
              <template slot="action" slot-scope="text, record">
                <a-button size="small" type="primary" @click="statisticsDetails(record)">查看</a-button>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-col>
    <a-col :md="6" :xs="24" style="padding: 0 10px;">
      <div class="btnBox">
        <a-button type="primary" v-if="routerShow($route,'data_getNewCollection')" :loading="loading" @click="getNewCollectionBtn">
          {{loading? '主动采集中' : '主动采集'}}
        </a-button>
        <a-button v-if="routerShow($route,'timing_add')" type="primary" @click="timingBtn">定时任务</a-button>
      </div>
      <div class="imgBox">
        <img v-if="itemDetail.img_pic" :src="itemDetail.img_pic" alt="设备图片">
        <span v-else style="color: #999;">无设备图片</span>
      </div>
      <ul class="contentBox">
        <li><label>连接状态：</label>{{itemDetail.status}}</li>
        <li><label>地理位置：</label>{{itemDetail.status}}</li>
        <li><label>隧道外尺寸：</label>
          长：{{itemDetail.tunnel_abroad_long}} 米
          宽：{{itemDetail.tunnel_abroad_width}} 米
          高：{{itemDetail.tunnel_abroad_height}} 米
        </li>
        <li><label>隧道长度：</label>{{itemDetail.tunnel_long}} 米</li>
        <li><label>可装载面：</label>
          宽：{{itemDetail.carry_width}}
          高：{{itemDetail.carry_height}}
          （单位：mm）
        </li>
        <li><label>选用棚板规格：</label>
          {{itemDetail.board_specs}}
        </li>
        <li><label>棚板安放：</label>
          {{itemDetail.board_put}}
        </li>
        <li><label>台车长度：</label>
          {{itemDetail.trolley_long}}
        </li>
        <li><label>台车数：</label>
          {{itemDetail.trolley_num}}
        </li>
        <li><label>窑内总容积：</label>
          {{itemDetail.kiln_volume}}
        </li>
        <li><label>台车面积：</label>
          {{itemDetail.trolley_volume}}
        </li>
        <li><label>设备类型：</label>
          {{itemDetail.type_name}}
        </li>
        <!-- <li><label>MAC：</label>
          未对接，待定！！！
        </li>
        <li><label>IP地址：</label>
          未对接，待定！！！
        </li> -->
        <!-- <li><label>轮询周期：</label>
          未对接，待定！！！
        </li> -->
        <li><label>创建时间：</label>
          {{itemDetail.created_at}}
        </li>
        <!-- <li><label>客户电话：</label>
          未对接，待定！！！
        </li> -->
      </ul>
    </a-col>
  </a-row>
  <a-modal
      title="下发控制历史"
      v-model="visible"
      width="80%"
    >
      <a-range-picker class="mb10"  @change="onDateChange" /><!-- showTime -->
      <!-- @ok="handleOk" -->
      <a-table :pagination="false" :columns="registerItemFields" :dataSource="registerItemList.data"
      :rowKey="record => record.id" :scroll="{ y: 500 }">
      </a-table>
      <div class="pageBox">
          <a-pagination
            :total="registerItemList.total"
            :showTotal="total => `共 ${total} 条数据`"
            :pageSize="registerItemList.per_page"
            :defaultCurrent="1"
            @change="pageChange"
          />
        </div>
    </a-modal>
  
  </a-spin>
</div>
</template>

<script>
  import { mapState, mapActions } from 'vuex';
  import Vue from "vue";
  import moment from 'moment';
  import { USER } from "@/store/mutation-types";
  import { showErrors, showError, showSuccess } from '@/utils/showMsg';
// import { log } from 'util';
    export default {
      name: "RealTime",
      props: {
        itemDetail: {
          type: Object,
        }
      },
      data() {
        return {
          userData: '',
          loading: false,
          visible: false,
          //下发控制
          formItem: {
            register_id: '',
            data_value: '',
          },
          tabsKey: '1',
          /* 通用模块 */
            //列表
            tableLoad: false, //列表loading状态
            itemFormList: {
              equipment_id: null,
            },
          /* 通用模块end */
          First:{
              grid: {
                // containLabel: true
                top: 10,
                bottom: 10,
                // left: 40,
              },
              xAxis: {
                  type: 'category',
                  boundaryGap: false,
                  data: [],
                  show: false,
              },
              yAxis: {
                  type: 'value',
                  scale: true,
                  show: false,
                  inverse:true
              },
              series: [{
                  data: [],
                  type: 'line'
              }]
          },

          // 临时
          Fields3: [
            {
                title: '数据名称',
                dataIndex: 'a',
                key: 'a',
                align: 'center',
                // scopedSlots: { customRender: 'a' },
                width: 100
            },
            {
                title: '数据值',
                dataIndex: 'b',
                key: 'b',
                align: 'center',
                width: 100
            },
            {
                title: '操作',
                dataIndex: 'c',
                key: 'c',
                align: 'center',
                width: 100
            },
            {
                title: '历史',
                dataIndex: 'd',
                key: 'd',
                align: 'center',
                width: 100
            },
          ],
          // Fields3: ,
          NewDataItem: [],
          registerForm: {
            register_id: '',
            page:1
          }
        }
      },
      computed: {
        ...mapState({
          requestCode: state => state.controlCenter.requestCode,
          // 实时数据
          NewDataLists: state => state.controlCenter.NewDataLists,
          NewDataFields: state => state.controlCenter.NewDataFields,
          // 设备控制信息
          SendRegisterLists: state => state.controlCenter.SendRegisterLists,
          SendRegisterFields: state => state.controlCenter.SendRegisterFields,
          // 设备控制信息历史
          registerItemList: state => state.controlCenter.registerItemList,
          registerItemFields: state => state.controlCenter.registerItemFields,

          //统计信息
          StatisticsLists: state => state.controlCenter.StatisticsLists,
          StatisticsFields: state => state.controlCenter.StatisticsFields,
        }),
        newID() {
          return this.itemDetail.id
        },
        isAdmin() {
          if (this.userData.role_grade === 1) {
              return true;
          } else {
              return false;
          }
        }
      },
      watch:{
        NewDataLists(newVal, oldVal){
          setTimeout(() => {
            this.drawLine()
            this.tableLoad = false
          }, 500);
        },
        newID:{
          handler(newVal, oldVal){
            this.changeData()
          },
          deep:true
        },
      },
      mounted() {
        this.userData = Vue.ls.get(USER);
        this.changeData()
      },
      methods: {
        // 下发控制历史时间筛选
        onDateChange(date,dateStrings) {
          console.log(date,dateStrings);
          // 'YYYY-MM-DD HH:mm:ss'
          this.registerForm.created_start = dateStrings[0]
          this.registerForm.created_end = dateStrings[1]
          this.registerForm.page = 1
          if (!date.length) {
            delete this.registerForm.created_start
            delete this.registerForm.created_end
          }
          this.getRegisterSendRecordList(this.registerForm)
        },
        timingBtn(){
          let equipmentId = this.newID   //设备id
          this.$router.push({
            path: '/timing/Monitor',
            query: {
              equipmentId : equipmentId,
            }
          })
        },
        // 控制信息详情
        statisticsDetails(item) {
          let equipmentId = this.newID   //设备id
          // let registerId = item.id   //寄存器id
          this.$router.push({
            path: '/data_center/statistics',
            query: {
              equipmentId : equipmentId,
            }
          })
        },
        controlDetails(item) {
          console.log(item);
          this.registerForm = {
            register_id: item.id,
            page: 1,
          }
          this.getRegisterSendRecordList(this.registerForm)
          this.visible = true
        },
        // 下发控制Btn
        controlBtn(item){
          console.log(item);
          const that = this
          this.formItem.register_id = item.id
          if (item.type == 2) {
            item.isSwitch ? this.formItem.data_value = 'FF00' : this.formItem.data_value = '0000'
          } else {
            this.formItem.data_value = item.equipment_data
          }
          this.$confirm({
            title: '确定下发？',
            onOk() {
              console.log(that.formItem);
              that.submitControl(that.formItem)
              console.log(that.requestCode);
              if (that.requestCode == 0) {
                setTimeout(() => {
                  that.changeData()
                }, 1000);
              }
            },
          });
        },
        //主动采集
        getNewCollectionBtn(){
          const that = this
          let equipmentId = this.newID   //设备id
          this.$confirm({
            title: '是否确定操作?',
            onOk() {
              const hide = that.$message.loading('采集中，请耐心等待...', 0);
              that.loading = true
              that.getNewCollectionFun({equipment_id: equipmentId}).then(response => {
                console.log(response);
                if (response.data.errorCode === 0) {
                  showSuccess( response.data.result )
                  setTimeout(hide,500);
                  that.loading = false
                  setTimeout(() => {
                    that.changeData()
                  }, 1000);
                } else {
                  showError( response.data.message )
                  setTimeout(hide,500);
                  that.loading = false
                }
              })
              .catch(error => {
                  showError( '请求出错' )
                  setTimeout(hide, 500)
                  that.loading = false
              });
            },
          });
        },
        /* 通用模块 */
        ...mapActions({
          getNewDataLists: 'controlCenter/getNewDataLists', //设备实时数据
          getStatisticsLists: 'controlCenter/getStatisticsLists', //设备统计
          getSendRegisterLists: 'controlCenter/getSendRegisterLists', //设备控制
          getNewCollectionFun: 'controlCenter/getNewCollectionFun', //主动采集
          submitControl: 'controlCenter/submitControl', //下发控制
          getRegisterSendRecordList: 'controlCenter/getRegisterSendRecordList', //下发控制历史
        }),
        // 重新获取列表数据
        changeData() {
          this.tableLoad = true
          this.itemFormList.equipment_id = this.newID
          if (this.routerShow(this.$route,'data_newData')) {
            this.getNewDataLists(this.itemFormList)
          } else {
            setTimeout(() => {
              this.tableLoad = false
            }, 1000);
          }
          if (this.routerShow(this.$route,'data_statistics')) {
            this.getStatisticsLists(this.itemFormList)
          }
          if (this.isAdmin && this.routerShow(this.$route,'data_sendRegister')) {
            this.getSendRegisterLists(this.itemFormList)
          }
        },
        // 页码
        pageChange(page) {
          this.registerForm.page = page;
          this.getRegisterSendRecordList(this.registerForm)
        },
        /* 通用模块end */
        details(item) {
          let equipmentId = this.newID   //设备id
          let registerId = item.type_id   //寄存器id
          this.$router.push({
            path: '/data_center/history',
            query: {
              equipmentId,
              registerId,
            }
          })
        },
        drawLine() {
          const that = this
          // this.NewDataItem = []
          // console.log(111111111111111111111111111,this.NewDataLists);
          this.NewDataLists.forEach((newData,i) => {
            let trendline = this.$echarts.init(this.$refs[`trend${newData.type_id}`]);
            // this.NewDataItem.push(trendline)
            trendline.setOption(this.First);
            trendline.setOption({
              xAxis : [
                {
                  data : newData.item,
                }
              ],
              series: {
                data: newData.item,
              }
            });
            window.addEventListener("resize", function() {
              trendline.resize();
            });
            // window.onresize = () => {
            //   trendline.resize();
            // };
          });
        }
      }
    }
</script>

<style scoped>
.card-container {
  background: #F5F5F5;
  overflow: hidden;
  padding: 24px;
}
.card-container > .ant-tabs-card > .ant-tabs-content {
  height: 120px;
  margin-top: -16px;
}

.card-container > .ant-tabs-card > .ant-tabs-content > .ant-tabs-tabpane {
  background: #fff;
  padding: 16px;
}

 >>> .card-container > .ant-tabs-card > .ant-tabs-bar {
  border-color: #fff;
  margin: 0 0 0 0;
  border-bottom: 1px solid #e8e8e8;
  outline: none;
  -webkit-transition: padding 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  transition: padding 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.card-container > .ant-tabs-card > .ant-tabs-bar .ant-tabs-tab {
  border-color: transparent;
  background: transparent;
}

.card-container > .ant-tabs-card > .ant-tabs-bar .ant-tabs-tab-active {
  border-color: #fff;
  background: #fff;
}

.btnBox {
  display: flex;
  justify-content: space-between;
  margin: 10px auto 0px;
}

.imgBox {
  width: 100%;
  height: 230px;
  background: rgb(232,232,232);
  overflow: hidden;
  margin: 20px auto;
}

.imgBox img {
  height: 100%;
  display: block;
  margin:  0 auto;
}

.imgBox span {
  height: 230px;
  display: block;
  line-height: 230px;
  text-align: center;
}

.contentBox li {
  padding-top: 6px;
  border-bottom: 1px solid rgba(187, 187, 187, 0.5);
}

</style>
